import { Inject, Provide } from '@midwayjs/core';
import { User } from '../entity/user.entity';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { JwtService } from '@midwayjs/jwt';

@Provide()
export class LoginService {
  @InjectEntityModel(User)
  user: Repository<User>;
  @Inject()
  jwt: JwtService;
  async login(options: { name: string; password: string }) {
    // 先去查找用户名密码是否正确
    const user = await this.user.findOne({
      where: {
        name: options.name,
        password: options.password,
      },
    });

    if (!user) {
      // 当未找到用户，返回用户名或者密码错误
      return {
        code: 1,
        message: '用户名或者密码错误',
      };
    }
    // 这里同时需要发放token
    const token = await this.jwt.sign({
      id: user.id,
      name: user.name,
    });

    return {
      code: 200,
      message: '登录成功',
      data: {
        token,
        user,
      },
    };
  }
}
